﻿namespace EasyWeb
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Data;
    using EasyWeb.Data;
    using EasyWeb.Design;

    [EWDisplayName(Name = "FieldDefinitionLookup", ResourceType = typeof(EWFieldDefinitionResources))]
    public class EWFieldDefinitionLookup : EWFieldDefinition
    {
        [Display(ResourceType = typeof(EWFieldDefinitionResources), Name = "FieldDefinition_AllowDefaultValue")]
        public override bool AllowDefaultValue
        {
            get { return false; }
        }

        [Display(ResourceType = typeof(EWFieldDefinitionResources), Name = "FieldDefinition_AllowUnique")]
        public override bool AllowUnique
        {
            get { return true; }
        }

        [Display(ResourceType = typeof(EWFieldDefinitionResources), Name = "FieldDefinition_DefaultValue")]
        public override object DefaultValue
        {
            get { throw new NotSupportedException(); }
            set { throw new NotSupportedException(); }
        }

        [Display(ResourceType = typeof(EWFieldDefinitionResources), Name = "FieldDefinitionLookup_LookupEntityId")]
        public Guid LookupEntityId
        {
            get { return this.StateBag.Get<Guid>("LookupEntityId"); }
            set { this.StateBag.Set("LookupEntityId", value); }
        }

        public override EWFieldDefinitionColumnCollection CreateFieldDefinitionColumns()
        {
            return new EWFieldDefinitionColumnCollection()
            {
                new EWFieldDefinitionColumn()
                {
                    Name = this.InternalName,
                    IsNullable = this.AllowNull,
                    IsUnique = this.AllowUnique && this.IsUnique,
                    Type = DbType.Guid
                }
            };
        }

        public override void Deserialize(EWSerializationInfo info)
        {
            base.Deserialize(info);

            this.LookupEntityId = info.GetGuid("LookupEntityId");
        }

        public override void Serialize(EWSerializationInfo info)
        {
            base.Serialize(info);

            info.AddValue("LookupEntityId", this.LookupEntityId);
        }
    }
}
